'use client'

import { useEffect, useState } from 'react'
import { useParams } from 'next/navigation'
import Image from 'next/image'
import api from '@/lib/api'
import BookingForm from '@/components/spots/BookingForm'
import { Button } from '@/components/ui/button'
import { ArrowLeft } from 'lucide-react'
import Link from 'next/link'
import { Suspense } from 'react'
import Loading from '@/components/ui/loading'
import { useIsMounted } from '@/hooks/useIsMounted'
import FavoriteButton from '@/components/spots/FavoriteButton'
import { toast } from 'react-hot-toast'
import { format } from 'date-fns'
import { zhCN } from 'date-fns/locale'

interface Review {
  id: number
  rating: number
  comment: string
  commented_at: string
  user: {
    username: string
  }
}

interface Spot {
  id: number
  name: string
  description: string
  location: string
  type: string
  open_time: string
  price: number
  images: string
  inventory: number
  rating: number
  reviews: Review[]
}

export default function SpotDetailPage() {
  const params = useParams()
  const isMounted = useIsMounted()
  const [spot, setSpot] = useState<Spot | null>(null)
  const [loading, setLoading] = useState(true)
  const [isFavorited, setIsFavorited] = useState(false)

  useEffect(() => {
    const fetchSpot = async () => {
      try {
        setLoading(true)
        const response = await api.get(`/api/spots/${params.id}`)
        setSpot(response.data)
      } catch (error) {
        console.error('Failed to fetch spot:', error)
      } finally {
        setLoading(false)
      }
    }

    if (isMounted) {
      fetchSpot()
    }
  }, [params.id, isMounted])

  useEffect(() => {
    const checkFavoriteStatus = async () => {
      try {
        const response = await api.get('/api/favorites')
        const favorites = response.data
        setIsFavorited(favorites.some((fav: any) => fav.spot.id === Number(params.id)))
      } catch (error) {
        console.error('Failed to check favorite status:', error)
      }
    }

    if (isMounted) {
      checkFavoriteStatus()
    }
  }, [params.id, isMounted])

  const handleFavorite = async () => {
    try {
      if (isFavorited) {
        await api.delete(`/api/favorites/${params.id}`)
        toast.success('取消收藏成功')
      } else {
        await api.post(`/api/favorites/${params.id}`)
        toast.success('收藏成功')
      }
      setIsFavorited(!isFavorited)
    } catch (error) {
      toast.error('操作失败')
    }
  }

  if (!isMounted) {
    return null
  }

  if (loading) {
    return <Loading />
  }

  if (!spot) {
    return <div>景点不存在</div>
  }

  return (
    <div className="bg-white">
      <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 py-8">
        <div className="mb-6 flex justify-between items-center">
          <Link href="/spots">
            <Button variant="ghost" className="flex items-center gap-2">
              <ArrowLeft className="h-4 w-4" />
              返回景点列表
            </Button>
          </Link>
          <FavoriteButton
            spotId={spot.id}
            isFavorited={isFavorited}
            onToggle={() => setIsFavorited(!isFavorited)}
          />
        </div>
        
        <div className="lg:grid lg:grid-cols-2 lg:gap-x-8">
          {/* 图片展示 */}
          <div className="aspect-h-3 aspect-w-4 overflow-hidden rounded-lg">
            <Image
              src={spot.images.split(',')[0]}
              alt={spot.name}
              width={800}
              height={600}
              className="h-full w-full object-cover object-center"
            />
          </div>

          {/* 景点信息 */}
          <div className="mt-8 lg:mt-0">
            <div className="flex items-center justify-between">
              <h1 className="text-3xl font-bold tracking-tight text-gray-900">{spot.name}</h1>
            </div>
            
            <div className="mt-4">
              <h2 className="sr-only">景点评分</h2>
              <div className="flex items-center">
                {[...Array(5)].map((_, i) => (
                  <svg
                    key={i}
                    className={`h-5 w-5 ${
                      i < spot.rating ? 'text-yellow-400' : 'text-gray-200'
                    }`}
                    fill="currentColor"
                    viewBox="0 0 20 20"
                  >
                    <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                  </svg>
                ))}
                <span className="ml-2 text-sm text-gray-500">{spot.rating} 分</span>
              </div>
            </div>

            <div className="mt-8">
              <div className="space-y-6">
                <p className="text-base text-gray-900">{spot.description}</p>

                <div className="mt-4">
                  <h3 className="text-sm font-medium text-gray-900">景点类型</h3>
                  <p className="mt-2 text-sm text-gray-500">{spot.type}</p>
                </div>

                <div className="mt-4">
                  <h3 className="text-sm font-medium text-gray-900">开放时间</h3>
                  <p className="mt-2 text-sm text-gray-500">{spot.open_time}</p>
                </div>

                <div className="mt-4">
                  <h3 className="text-sm font-medium text-gray-900">地址</h3>
                  <p className="mt-2 text-sm text-gray-500">{spot.location}</p>
                </div>
              </div>
            </div>

            <div className="mt-8">
              <BookingForm
                spotId={spot.id}
                price={spot.price}
                inventory={spot.inventory}
              />
            </div>
          </div>
        </div>

        <div className="mt-16">
          <h2 className="text-2xl font-bold tracking-tight text-gray-900 mb-8">用户评价</h2>
          <div className="space-y-8">
            {spot.reviews.length > 0 ? (
              spot.reviews.map((review) => (
                <div key={review.id} className="border-b pb-8 last:border-b-0">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center">
                      <span className="font-medium text-gray-900">
                        {review.user.username}
                      </span>
                      <span className="mx-2 text-gray-300">•</span>
                      <span className="text-sm text-gray-500">
                        {format(new Date(review.commented_at), 'yyyy年MM月dd日', { locale: zhCN })}
                      </span>
                    </div>
                    <div className="flex items-center">
                      {[1, 2, 3, 4, 5].map((value) => (
                        <svg
                          key={value}
                          className={`h-5 w-5 ${
                            value <= review.rating ? 'text-yellow-400' : 'text-gray-200'
                          }`}
                          fill="currentColor"
                          viewBox="0 0 20 20"
                        >
                          <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                        </svg>
                      ))}
                    </div>
                  </div>
                  <p className="mt-4 text-gray-600">{review.comment}</p>
                </div>
              ))
            ) : (
              <div className="text-center text-gray-500 py-8">
                暂无评价
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  )
} 